include("util.js");
include("tinyxmldom.js");

var karotz_ip="localhost";
//var karotz_ip="192.168.0.15";

var URL=params[instanceName].RATPURL;	//URL du type : http://www.ratp.fr/horaires/fr/ratp/bus/prochains_passages/PP/B62/62_1299_13013/A
var vers=params[instanceName].version;	//VC ou VL
//var URL="http://www.ratp.fr/horaires/fr/ratp/bus/prochains_passages/PP/B62/62_1299_13013/A";
//var vers="VC";
//log("URL : "+URL);

var XmlData = http.get(URL);
//log("XmlData : "+XmlData);
var objDom = new XMLDoc(XmlData);
var domTree = objDom.docNode;
//log("domTree : "+domTree);
var searchNode=domTree.getElementById("prochains_passages");
var domNode1=searchNode.selectNode("/fieldset/table/tbody/tr/td[1]");
//log("Node 1 : "+domNode1.getElements());
var nextBus=domNode1.getText();
//log("Bus 1 : "+nextBus);

var domNode2=searchNode.selectNode("/fieldset/table/tbody/tr[1]/td[1]");
//log("Node 2 : "+domNode2);
var followingBus=domNode2.getText();
//log("Bus 2 : "+followingBus);
nextBus=nextBus.replace("mn","minutes");
followingBus=followingBus.replace("mn","minutes");

var buttonListener = function(event) {
    if (event == "DOUBLE") {
        karotz.tts.stop();
        exit();
    }
    return true;
}

var exitFunction = function(event) {
  if(event == "CANCELLED" || event == "TERMINATED")  {
        exit();
    }
    return true;
}

var onKarotzConnect = function(data) {
	karotz.button.addListener(buttonListener);
	//log("NextBus : "+nextBus);
	//log("Following Bus : "+followingBus);
	karotz.tts.start("Prochain bus dans " + nextBus + ".", "fr", NextTTS);
}

var NextTTS = function(event) {
	if(event == "CANCELLED" || event == "TERMINATED")  {
		karotz.tts.start("Le suivant dans "+ followingBus + ".", "fr", exitFunction);
    }
}

karotz.connectAndStart(karotz_ip, 9123, onKarotzConnect, {});
